<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\controller\Base;
use app\common\model\CouponReceive;
use app\common\model\Danye;
use app\common\model\Order;
use app\common\model\OrderList;
use app\common\model\QyLevel;
use app\common\model\QyLevelJiang;
use app\common\model\Coupon;
use think\facade\Db;
use \think\Request;

class QuanYi extends Base
{
    /**
     * 权益中心
     * @param Request $request
     * @return \think\response\Json
     */
    public function quan_yi(Request $request)
    {
        $user = $this->getUser();
        $data = [];
        $data['user_img'] = imageUrl($user['headimg']);
        $data['quan_yi_level'] = \app\common\model\User::ou_qi_level($user['ou_qi_level'], $user['ou_qi']);

        $user_ou_qi_level = \app\common\model\User::where(['id' => $user['id']])->value('ou_qi_level');
        $level_list = QyLevel::getAllList([['level', '>', 0]], 'id,level', 'level asc');
        foreach ($level_list as $k => &$v) {
            $pu_jiang = QyLevelJiang::getAllList(['qy_level_id' => $v['id'], 'type' => 1], 'id,title,z_num,imgurl', 'id asc');
            $v['pu_jiang'] = $pu_jiang;

            $gao_jiang = QyLevelJiang::getAllList(['qy_level_id' => $v['id'], 'type' => 2], 'id,title,z_num,imgurl', 'id asc');
            foreach ($gao_jiang as $kk => &$vv) {
                $vv['imgurl'] = imageUrl($vv['imgurl']);
            }
            $v['gao_jiang'] = $gao_jiang;

            //是否可领取
            if ($user_ou_qi_level >= $v['level']) {
                $v['is_ling'] = 1;
            } else {
                $v['is_ling'] = 0;
            }
            //是否已领取
            $is_ling = Db::name('user_quan_yi_level_jiang')->where(['qy_level_id' => $v['id'], 'qy_level' => $v['level'], 'user_id' => $user['id']])->whereNull('deltime')->find();
            if ($is_ling) {
                $v['is_ling'] = 2;
            }
        }
        $data['level_list'] = $level_list;
        $data['danye_list'] = Danye::field('id,title,content')->whereIn('id', [1, 2])->select();

        return $this->renderSuccess('请求成功', $data);
    }

    /**
     * 领取
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function quan_yi_ling(Request $request)
    {
        $user = $this->getUser();
        $level_id = request()->param('id', 0);
        $qy_level = QyLevel::where(['id' => $level_id])->whereNull('deltime')->find();
        if (!$qy_level) {
            return $this->renderError('数据错误');
        }

        if ($qy_level['level'] > $user['ou_qi_level']) {
            return $this->renderError('暂未达到该等级');
        }

        $jiang = QyLevelJiang::where(['qy_level_id' => $qy_level['id']])->whereNull('deltime')->find();
        if (!$jiang) {
            return $this->renderError('奖品不存在');
        }
        $is_ling = Db::name('user_quan_yi_level_jiang')->where(['qy_level_id' => $qy_level['id'], 'qy_level' => $qy_level['level'], 'user_id' => $user['id']])->whereNull('deltime')->find();
        // if ($is_ling) {
        //     return $this->renderError('你已经领取过了');
        // }

        Db::startTrans();
        $return_data = [];
        $return_data2 = [];
        $insert_data = [];
        $insert_data2 = [];
        $res = [];
        try {
            //优惠券
            $jiang_list = QyLevelJiang::getAllList(['qy_level_id' => $qy_level['id'], 'type' => 1], '*', 'id asc');
            foreach ($jiang_list->toArray() as $k => &$v) {
                $insert_data[$k] = $v;
                $insert_data[$k]['user_id'] = $user['id'];
                $insert_data[$k]['end_time'] = $v['effective_day'] * 86400 + time();
                $insert_data[$k]['addtime'] = time();
                $insert_data[$k]['updatetime'] = time();
                unset($insert_data[$k]['id']);


                $return_data[$k]['id'] = $v['id'];
                $return_data[$k]['title'] = $v['title'];
                $return_data[$k]['type'] = $v['type'];
                $return_data[$k]['jian_price'] = $v['jian_price'];
                $return_data[$k]['man_price'] = $v['man_price'];
                $return_data[$k]['effective_day'] = $v['effective_day'];
                $return_data[$k]['end_time'] = date('Y-m-d H:i:s', $v['effective_day'] * 86400 + time());
                $return_data[$k]['z_num'] = $v['z_num'];
                $ttype = Coupon::where(['id'=>$v['coupon_id']])->value('ttype');
               
                //赠送优惠券
                for ($i = 0; $i < $v['z_num']; $i++) {
                    $res[] = CouponReceive::insert(
                        [
                            'user_id' => $user['id'],
                            'title' => $v['title'],
                            'price' => $v['jian_price'],
                            'man_price' => $v['man_price'],
                            'end_time' => $v['effective_day'] * 86400 + time(),
                            'addtime' => time(),
                            'coupon_id' => $v['id'],
                            'state' =>$ttype
                        ]

                    );
                }
            }

            //奖品
            $temp_data = [];
            $jiang_list2 = QyLevelJiang::getAllList([['qy_level_id', '=', $qy_level['id']], ['type', '=', 2], ['probability', '>', 0]], '*', 'id asc');

            foreach ($jiang_list2->toArray() as $kk => $vv) {
                $real_pro_count = $vv['probability'] * 100;
                $temp_data = array_merge($temp_data, array_fill(0, intval($real_pro_count), $vv));
            }

            if (count($temp_data) > 0) {
                shuffle($temp_data);
                shuffle($temp_data);
                $goods_list2 = $temp_data[0];

                $insert_data2[0] = $goods_list2;
                $insert_data2[0]['user_id'] = $user['id'];
                $insert_data2[0]['addtime'] = time();
                $insert_data2[0]['end_time'] = '';
                $insert_data2[0]['updatetime'] = time();
                unset($insert_data2[0]['id']);

                $return_data2[0]['title'] = $goods_list2['title'];
                $return_data2[0]['imgurl'] = $goods_list2['imgurl'] ? imageUrl($goods_list2['imgurl']) : '';
                $return_data2[0]['shang_id'] = $goods_list2['shang_id'];

                //赠送奖品
                $order_num = create_order_no('MH_', 'order', 'order_num');
                #创建订单
                $order_data = [
                    'user_id' => $user['id'],
                    'order_num' => $order_num,
                    'order_total' => 0,#订单金额
                    'order_zhe_total' => 0,#订单折扣金额
                    'price' => 0,#微信支付
                    'use_money' => 0,#余额抵扣
                    'use_integral' => 0,#潮币抵扣
                    'use_score' => 0,#积分抵扣
                    'zhe' => 0,#会员折扣
                    'goods_id' => 0,
                    'num' => 0,
                    'goods_price' => 0,
                    'goods_title' => 0,
                    'goods_imgurl' => 0,
                    'prize_num' => 0,
                    'status' => 0,
                    'pay_type' => 0,#1微信 2支付宝
                    'order_type' => 10,
                    'addtime' => time(),
                ];

                $res[] = $order_id = Order::insertGetId($order_data);
                $save_prize_info = [
                    'order_id' => 0,
                    'user_id' => $user['id'],
                    'status' => 0,#0未操作 1选择兑换 2选择发货
                    'goods_id' => 0,
                    'num' => 0,
                    'shang_id' => $goods_list2['shang_id'],
                    'goodslist_id' => 0,
                    'goodslist_title' => $goods_list2['title'],
                    'goodslist_imgurl' => $goods_list2['imgurl'],
                    'goodslist_price' => $goods_list2['jiang_price'],
                    'goodslist_money' => $goods_list2['money'],
                    'goodslist_type' => 1,
                    'addtime' => time(),
                    'prize_code' => $goods_list2['prize_code'],
                    'order_type' => 10,
                    'luck_no' => 0,
                ];
                #入库===
                $res[] = OrderList::insert($save_prize_info);
            }

            $result = Db::name('user_quan_yi_level_jiang')->insertAll(array_merge($insert_data, $insert_data2));

            if ($result && resCheck($res)) {
                Db::commit();
                return $this->renderSuccess('领取成功', array_merge($return_data, $return_data2));
            } else {
                Db::rollback();
                return $this->renderError('网络故障,请稍后再试');
            }
        } catch (\Exception $e) {
            Db::rollback();
            dd($e->getMessage());
            return $this->renderError('网络故障,请稍后再试');
        }

    }
}
